﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wechat.Util.Log4Net;
using Wechat.Util.ReturnMessage;
using Wechat.Util.StateCode;

namespace WeChat.Web.Filter
{
    public class LogHandleErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 对异常重写
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)//异常拦截器
        {
            Exception exception = filterContext.Exception;//获取错误信息

            if (filterContext.ExceptionHandled)//如果已处理异常，则返回
            {
                return;
            }

            HttpException httpException = new HttpException(null, exception);//初始化实力，获取异常信息

            LogHelper.WriteLog(typeof(LogHandleErrorAttribute), httpException);//输出日志

            filterContext.ExceptionHandled = true;//异常已处理

            if (filterContext.HttpContext.Request.IsAjaxRequest())//如果为ajax请求
            {
                var result = new ResultMessage()//对ajax返回错误信息进行弹框展示
                {
                    Code = (int)EnumStateCode.SystemError,
                    Data = exception,
                    Status = false,
                    Message = exception.Message
                };
                filterContext.Result = new JsonResult()
                {
                    Data = result,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                ViewDataDictionary dict = new ViewDataDictionary();
                dict.Add("ErrorMessage", exception.Message);//viewdate字典
                filterContext.Result = new ViewResult()//返回异常页
                {
                    ViewName = "Error",
                    ViewData = dict
                };
            }
        }
    }
}